<template>
    <div class="box">
        <div class="table-title">{{ definePropsMsg.tableTitle }}</div>
        <div class="table-action-box">
            <el-button type="primary" class="table-actionBox-addBtn" @click="adminOperate(0)">
                <span class="table-actionBox-addBtn-icon">+</span><span>新增</span>
            </el-button>
            <el-input v-model="searchInput" placeholder="请输入用户名/姓名" class="table-actionBox-searchInput">
                <template #suffix>
                    <el-icon @click="findAdmin" class="table-actionBox-searchInput-icon">
                        <search />
                    </el-icon>
                </template>
            </el-input>
        </div>
        <table class="table" v-loading="tableDataLoading">
            <tr>
                <th>管理员ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>排序</th>
                <th>添加时间</th>
                <th>操作</th>
            </tr>
            <tr v-if="tableData.length > 0" v-for="i of tableData">
                <td>{{ i.admin_id }}</td>
                <td>{{ i.admin_name }}</td>
                <td>{{ i.admin_name }}</td>
                <td>100</td>
                <td>{{ Format.timeFormat(i.create_time) }}</td>
                <td @click="adminOperate(i)" class="edit-btn">编辑</td>
            </tr>
            <tr v-else>
                <td colspan="6" style="border-bottom: none;">
                    <el-empty description="No Data" />
                </td>
            </tr>
        </table>
        <el-pagination v-if="tableData.length > 0" class="table-pagination" :page-size="tablePagination.pageSize"
            layout="prev, pager, next" :total="tablePagination.total" v-model:current-page="currentPage" />
    </div>

    <el-dialog v-model="addBtnDialogVisible" title="新增管理员" width="45%" :before-close="formHandleClose">
        <div class="dialog-box">
            <el-form ref="addAdminFormRef" :model="addAdminForm" :rules="addAdminFormRules" :label-width="100">
                <!-- <el-form-item label="管理员ID" prop="adminID">
                    <el-input v-model="addAdminForm.adminID" />
                </el-form-item> -->
                <el-form-item label="所属角色" prop="roleID">
                    <!-- <el-select v-model="addAdminForm.roleID" multiple placeholder="所属角色"> -->
                    <!-- 多选后重新登录返回的nav数据很奇怪 -->
                    <el-select v-model="addAdminForm.roleID" placeholder="所属角色">
                        <el-option v-for="i in adminFormMultiple" :key="i.id" :label="i.label" :value="i.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="addAdminForm.userName" />
                </el-form-item>
                <el-form-item label="用户密码" prop="pwd1">
                    <el-input type="password" show-password v-model="addAdminForm.pwd1"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="pwd2">
                    <el-input type="password" show-password v-model="addAdminForm.pwd2"></el-input>
                </el-form-item>
                <!-- <el-form-item label="排序" prop="slot">
                    <el-input-number v-model="addAdminForm.slot" :min="1" :max="100" controls-position="right" />
                </el-form-item> -->
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="formHandleClose()">取消</el-button>
                <el-button type="primary" @click="formHandleCofirm(0)">确定</el-button>
            </span>
        </template>
    </el-dialog>

    <el-dialog v-model="editBtnDialogVisible" title="编辑管理员" width="45%" :before-close="formHandleClose">
        <div class="dialog-box">
            <el-form ref="editAdminFormRef" :model="editAdminForm" :rules="editAdminFormRules" :label-width="100">
                <el-form-item label="管理员ID" prop="adminID">
                    <el-input-number v-model="editAdminForm.adminID" :precision="0" :step="1" :min='0'
                        :controls="false" />
                </el-form-item>
                <el-form-item label="所属角色" prop="roleID">
                    <el-select v-model="editAdminForm.roleID" placeholder="所属角色">
                        <el-option v-for="i in adminFormMultiple" :key="i.id" :label="i.label" :value="i.id" />
                    </el-select>
                </el-form-item>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="editAdminForm.userName" />
                </el-form-item>
                <el-form-item label="用户密码" prop="pwd1">
                    <el-input type="password" show-password v-model="editAdminForm.pwd1"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="pwd2">
                    <el-input type="password" show-password v-model="editAdminForm.pwd2"></el-input>
                </el-form-item>
                <!-- <el-form-item label="排序" prop="slot">
                    <el-input-number v-model="addAdminForm.slot" :min="1" :max="100" controls-position="right" />
                </el-form-item> -->
            </el-form>
        </div>
        <template #footer>
            <span class="dialog-footer">
                <el-button @click="formHandleClose()">取消</el-button>
                <el-button type="primary" @click="formHandleCofirm(1)">确定</el-button>
            </span>
        </template>
    </el-dialog>

</template>
<script setup>
import { ref, getCurrentInstance, watch, reactive, nextTick } from 'vue';
import { Format } from '/util/CommonFunctions.js'
import { ElMessageBox, ElMessage } from 'element-plus';
const { proxy } = getCurrentInstance()
const token = window.localStorage.getItem('token')

let definePropsMsg = defineProps(['tableTitle']) //从父组件接收到的表格标题

const adminFormMultiple = [ //下拉菜单选择项
    { id: 1, label: '超级管理员' },
    { id: 2, label: '测试角色' },
    { id: 3, label: '待定1' },
    { id: 4, label: '待定2' },
    { id: 5, label: '待定3' },
]
// ------------------------------------------------------------------------------------------新增------
let addBtnDialogVisible = ref(false) // 新增 模态框显隐状态
let addAdminFormRef = ref() // ref获取表单子组件
let addAdminForm = reactive({ roleID: [], userName: '', pwd1: '', pwd2: '' }) //校验前的数据
const addAdminFormRules = reactive({ // 校验规则
    roleID: [{ required: true, message: '请选择角色' }],
    userName: [{ required: true, trigger: 'blur', message: '请输入至少4个字符', min: 4 }],
    pwd1: [{ required: true, trigger: 'blur', message: '请输入密码' }],
    pwd2: [{ required: true, validator: formAddPwdCheck, trigger: 'blur' }],
})
// ------------------------------------------------------------------------------------------新增------

// ------------------------------------------------------------------------------------------编辑------
let editBtnDialogVisible = ref(false) // 编辑 模态框显隐状态
let editAdminFormRef = ref() // ref获取表单子组件
let editAdminForm = reactive({ adminID: undefined, roleID: [], userName: '', pwd1: '', pwd2: '' }) //校验前的数据
const editAdminFormRules = reactive({ // 校验规则
    roleID: [{ required: true, message: '请选择角色', trigger: blur }], // 验证时机为blur
    adminID: [{ required: true, message: '请输入非负整数', trigger: 'blur' }],
    userName: [{ required: true, trigger: 'blur', message: '请输入至少4个字符', min: 4 }],
    pwd1: [{ trigger: 'blur', message: '请输入密码' }],
    pwd2: [{ trigger: 'blur', validator: formEditPwdCheck, trigger: 'blur' }],
})
// ------------------------------------------------------------------------------------------编辑------

let searchInput = ref()

let tableData = ref([])
let tablePagination = ref({ pageSize: 12, count: 0 }) // 分页
let tableDataLoading = ref(true)

let currentPage = ref(1) // 分页激活项 默认第一页

loadTableData()

watch(
    () => currentPage.value,
    (newVal, oleVal) => { loadTableData(newVal) },
)

function loadTableData(p, s) { // 加载文章列表 这里用的是最高一级的信息 每一条下的roles是啥
    tableDataLoading.value = true
    const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/accountList', { page: p ? p + '' : '1', size: s ? s + '' : tablePagination.value.pageSize, token: token })
    promiseRes.then(res => {
        let resData = res.data.data
        tableData.value = resData.data || []
        tablePagination.value.total = resData.count
        tableDataLoading.value = false
    })
}
function adminOperate(e) { //新增按钮 编辑按钮 e为当前条目 不传为编辑
    if (e === 0) {
        addBtnDialogVisible.value = true
        nextTick(() => { console.log('新增'); addAdminFormRef.value.resetFields() }) // 点击的时候模态框可能没有加载完毕 需要nextTick 等待后再ref出其中的方法
    }
    else {
        editBtnDialogVisible.value = true
        let temp = []
        if (e.roles.length > 0) { e.roles.map(i => { temp.push(i.role_id) }) }
        if (temp[0] <= 5) { editAdminForm.roleID = temp[0] } else { editAdminForm.roleID = 1 }
        editAdminForm.adminID = e.admin_id
        editAdminForm.userName = e.admin_name
        editAdminForm.pwd1 = e.pw
    }
}
function formHandleClose(e) {
    if (addAdminFormRef.value != undefined) { addAdminFormRef.value.resetFields(); addBtnDialogVisible.value = false } // 重置表单数据
    if (editAdminFormRef.value != undefined) { editAdminFormRef.value.resetFields(); editBtnDialogVisible.value = false }
}
function formHandleCofirm(e) { // 新增或修改管理员 表单校验 //提交 请求 e为未校验的表单数据
    if (e === 0) { //新增
        let query = { name: addAdminForm.userName, pw: addAdminForm.pwd1, roles: [addAdminForm.roleID], token: token } // 单选时
        addAdminFormRef.value.validate((valid, fields) => { //ref获取表单子组件 valid为校验结果 fields为未通过验证的表单项
            if (valid) { // 检验通过
                const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/register', query)
                promiseRes.then((res) => {
                    if (res.data.msg != "") { ElMessage.warning(`操作失败：${res.data.msg}`) }
                    else {
                        loadTableData(1) // 刷新列表
                        addAdminFormRef.value.resetFields() // 重置表单数据
                        addBtnDialogVisible.value = false; // 关闭模态框
                        ElMessage.success(`操作成功，用户名：${res.data.data.admin_name}`); // 提示信息
                    }
                })
            }
            else { console.log('error', fields); } // 未通过 打印未通过的表单项
        })
        console.log(query);
    }
    else { // 编辑
        let query = { name: editAdminForm.userName, pw: editAdminForm.pwd1, roles: [editAdminForm.roleID], token: token, admin_id: parseInt(editAdminForm.adminID) } // 单选时
        editAdminFormRef.value.validate((valid, fields) => {
            if (valid) {
                console.log(query);
                console.log(parseInt(editAdminForm.adminID));
                const promiseRes = proxy.$reqFuncAxios('post', 'api/admin/register', query)
                promiseRes.then((res) => {
                    if (res.data.msg != "") { ElMessage.warning(`操作失败：${res.data.msg}`) }
                    else {
                        loadTableData(1) // 刷新列表
                        editAdminFormRef.value.resetFields() // 重置表单数据
                        editBtnDialogVisible.value = false; // 关闭模态框
                        ElMessage.success(`操作成功，用户名：${res.data.data.admin_name}`); // 提示信息
                    }
                })
            }
            else { console.log('error', fields); } // 未通过 打印未通过的表单项
        })
    }
}
function formAddPwdCheck(rule, value, callbackFun) { // 针对pwd2进行密码校验 rule为当条数据的校验规则 // add
    if (!value) { return callbackFun(new Error('请再次输入相同的密码')) } // 回调函数中的新Error优先级小于rules内的
    if (addAdminForm.pwd1 != value) { callbackFun(new Error('两次密码不同，请确认后再输入')) }
    else { callbackFun() }
}
function formEditPwdCheck(rule, value, callbackFun) { // 针对pwd2进行密码校验 rule为当条数据的校验规则 // edit
    if (value) { if (editAdminForm.pwd1 != value) { callbackFun(new Error('两次密码不同，请确认后再输入')) } } ///若输入了 则必须两者相同 未输入或已清空则不管
    callbackFun()
}
function findAdmin() {
    console.log('findAdmin');
}

</script>
<style scoped>
.box {
    margin: 16px 20px;
    padding: 24px;
    background-color: #fff !important;
    display: block !important;
    min-width: fit-content;
}

.table-title {
    font-size: 16px;
    color: rgba(0, 0, 0, .75);
    margin-bottom: 16px;
}

.table-action-box {
    margin-bottom: 18px;
    display: flex;
    justify-content: space-between;

    line-height: 1.5;
    color: rgba(0, 0, 0, .65);
    transition: all .3s;
}

.table-actionBox-addBtn {
    border-radius: 2px;
    transition: all .3s;
}

.table-actionBox-addBtn-icon {
    margin-right: 5px;
    font-size: 20px;
}

.table-actionBox-searchInput {
    width: 300px;
}

.table-actionBox-searchInput-icon {
    cursor: pointer;
    transition: all .3s;
    font-size: 16px;
}

.table-actionBox-searchInput-icon:hover {
    color: #409EFF;
}

.dialog-box {
    margin: 0 100px;
}

/*
.dialog-box :deep() .el-input__inner {
    text-align: left;
}

.dialog-box :deep() .el-form-item__content .el-input-number,
.dialog-box :deep() .el-form-item__content .el-select {
    flex-grow: 1;
}

.dialog-box :deep() .el-dialog__body {
    border-top: 1px solid #e8e8e8;
    border-bottom: 1px solid #e8e8e8;
    padding: 20px;
    box-sizing: border-box;
}

.dialog-box :deep() .el-dialog__title {
    font-size: 16px;
}

.dialog-box :deep() .el-dialog__header {
    padding: 16px 20px;
} */

.edit-btn {
    color: #1890ff;
    text-decoration: none;
    background-color: transparent;
    outline: none;
    cursor: pointer;
    transition: color .3s;
}

.edit-btn:hover {
    color: #40a9ff;
}

.table-pagination {
    margin: 0 auto;
    width: fit-content;
    margin-top: 20px;
}
</style>